import {
  createStore
} from './redux'

const counter = document.getElementById('counter')
const addButton = document.getElementById('add-button')
const minusButton = document.getElementById('minus-button')

const ADD = 'ADD'
const MINUS = 'MINUS'

const initialState = { number: 0 }

/**
 * 根据动作创建新的状态
 * @param {*} state 老状态
 * @param {*} action 动作
 */
function reducer(state = initialState, action) {
  switch (action.type) {
    case ADD:
      return { number: state.number + 1 }
    case MINUS:
      return { number: state.number - 1 }
    default:
      return state
  }
}

const store = createStore(reducer)

function render() {
  counter.innerHTML = store.getState().number
}

render()

store.subscribe(render) // 当状态发生变化重新执行 render 方法

addButton.addEventListener('click', () => {
  store.dispatch({ type: ADD })
})
minusButton.addEventListener('click', () => {
  store.dispatch({ type: MINUS })
})
